package com.example.design.singleton;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName Singleton10
 * @Description 使用互斥锁，实现双重检查加锁单例模式
 * @Author Administrator
 * @Date 2020/5/7 13:14
 * @Version 1.0
 */
public class Singleton10 {

    private static volatile Singleton10 instance;
    // 可重入锁
    private static final ReentrantLock lock = new ReentrantLock();
    private Singleton10(){}

    public static Singleton10 getInstance(){
        if(instance == null){
            lock.lock();
            try{
                if(instance == null){
                    instance = new Singleton10();
                }
            } catch (Exception e ){
                // ......
            } finally {
                lock.unlock();
            }
        }
        return instance;
    }

    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public static void main(String[] args) {
        Singleton10 s1 = Singleton10.getInstance();
        Singleton10 s2 = Singleton10.getInstance();
        s1.setName("zhangsan10");
        s2.setName("lisi10");
        System.out.println(s1.getName());
        System.out.println(s2.getName());
        System.out.println(s1.getName().equals(s2.getName()));
    }

}
